import {action, observable, computed} from 'mobx';
import * as API from '../apis/req';
import base from '../util/base';
import { toJS } from 'mobx';
import * as type from "../constants/type";
import { buildUrlStr } from '../util/formUtil';
import * as formUtil from '../util/formUtil'
export default class wfSmartGuessStore {

  @observable smartGuessStatus = false; //智能预测开启，展开简易视图
  @observable allMapshow = false; //完整视图

  @observable baseReqParams = {};


  @observable divideNodeArr = []; //分叉节点状态存储器
  @observable nodeArr = []; //节点数据
  @observable stopGetArrFlag = false;
  @observable needloading = false;
  data = {}; //getsimpleData接口获取的数据
  @observable forecastInfoMap = observable.map ? observable.map({}) : asMap({});
  
  @observable controlWranWrapFlag = false;
  @observable needShowTip = false; //是否需要显示已经预测者的信息
 
  @observable operatorInfo = [];
  @observable operatorMap = observable.map? observable.map({}): asMap({}); //操作者信息

  @observable needForecastFunc = false;

  @observable stopResetFlag = false;
  @observable clickedMap = observable.map ? observable.map({}) : asMap({}); 

  @observable justdoOnce = true;
  @observable needBtnMask = false;
  @observable showDescriptWord = false;

  @observable endflage = false;
  clientWidth = 0;
  @observable isEnd = false;
  @observable forecastUrl = '';
  @observable hasResultFlag = false;
  iframeHeight = 0;
 
  switchStatus = {
    "openAutoForecast": '0', //是否开启智能预测
    "showAutoForecastResult": '0' //默认显示智能预测视图 '1': pc端 '2': 移动端
  }

  @action('初始化请求接口的params参数')
  init = (commonParam = {}) =>  {
    let logParams = {};
    const { commonParam:{isFree,currentnodetype} } = base.globalStore;
    const baseParamKey = [ "requestid", "requestType", "workflowid"];
    const switchParamsKey = ["openAutoForecast", "showAutoForecastResult" ];
    baseParamKey.map( v => {logParams[v] = commonParam[v]});
    switchParamsKey.map( v => {this.switchStatus[v] = commonParam[v]});
    this.baseReqParams = logParams;

    if(logParams.requestid 
      && logParams.requestid != -1 
      && isFree != 1 
      && currentnodetype 
      && currentnodetype != '3'
      && this.switchStatus['openAutoForecast']
      && this.switchStatus['openAutoForecast'] == '1'
      ) {
        this.openForecastFunc(true); //显示智能预测功能按钮
        if(this.switchStatus['showAutoForecastResult'] 
            && this.switchStatus['showAutoForecastResult'].indexOf('1') > -1 ) {
              this.clickSmartBtn(); //显示智能预测结果
          }
      }
  }

  @action('设置iframe的src')
  setIframeSrc = () => {
    this.forecastUrl = formUtil.getIframeUrl({requestid: this.baseReqParams.requestid}) + '&showForecastNode=1';
    this.iframeHeight = jQuery('.map-box-show').height() - jQuery('.wf-map-header').outerHeight() - 5 + 'px';
  }
  @action('开启智能预测功能')
  openForecastFunc = bool => {
    this.needForecastFunc = bool;
  }
 
  @action('修改变量值')
   setState = (obj = {}) => {
    const keys = Object.keys(obj);
    for(let key of keys) {
      this[key] = obj[key];
    }
  }
 
  @action('模拟智能预测按钮点击')
  clickSmartBtn = () => {
    this.smartGuessStatus = true;
    this.allMapshow = false;
    this.setRecordClicked('smart-btn-click');
    this.justdoOnce = false;
    this.getForecastInfo();
    this.getCellArr();
  }

  @action('获取前预测者操作信息') 
  getForecastInfo = () => {
    let params = {requestid: this.baseReqParams.requestid};
    API.getForecastInfo(params).then( data => {
      this.needShowTip = data.showTip;
      if(data.forecastInfo && this.baseReqParams.requestid > 0) {
        this.forecastInfoMap.set(this.baseReqParams.requestid,  data.forecastInfo);
      }
    })
  }

  @action('获取预测节点数据')
  getCellArr = (params, callbackFun) => {
    let newParams = {...this.baseReqParams, ...params};
    API.getSimpleWfData(newParams).then( (data) => {
    this.data = data; 
    this.hasResultFlag = true;
    this.isEnd = data.forecastInfo.isEnd;
    if(!data.forecastInfo) {
      this.stopGetArrFlag = true;
      this.needBtnMask = false;
      return this.nodeArr = []
    }
    
    if(data.forecastInfo.isEnd) {
      this.needloading = false; 
      this.stopGetArrFlag = true;
      this.needBtnMask = false;
      callbackFun && callbackFun();
    } else  {
      this.stopGetArrFlag = false;
    }
     //分叉节点的遍历
     data.nodeInfo && data.nodeInfo.map((item) => {
      if(item.branchNumber > 1) { 
        if(this.divideNodeArr.length == 0) {
          this.divideNodeArr.push(
            {
              id: item.nodeid, 
              remark:item.nodeRemark,
              checkItem: item.currentBranch, 
              showStatus: false
            });
        } else {
          if( this.divideNodeArr.every( v => {
            if(v.remark == item.nodeRemark) {
              v.checkItem = item.currentBranch;
              return false;
            }
            return true;
          })){
            this.divideNodeArr = [...this.divideNodeArr, {id: item.nodeid, remark:item.nodeRemark, checkItem: item.currentBranch, showStatus: false}]

          }
        }
      }
    })
    this.nodeArr = data.nodeInfo || [];
  })
}
  @action('设置loading加载图')
  setLoadingWrap = ( bool ) => {
    this.needloading = bool;
  }
  @action('重新预测节点') 
  getResetForecast = (callbackFun) => {
    this.getCellArr({resetForecast: 1}, callbackFun);
  } 

  @action('开启智能预测与否')
  changSmartGuessStatus = () => {
  this.smartGuessStatus = !this.smartGuessStatus
  }

  @action('设置下拉选择框显隐')
  setShowSelectPanel = (obj) =>{
    this.divideNodeArr.map( (v) => {
      if(v.remark == obj) v.showStatus = !v.showStatus; 
    })
  }
  @action('隐藏所有显示的下拉框') 
  setHiddenSelectPanel = () => {
    this.divideNodeArr.map( v => {
      if(v.showStatus) {
        v.showStatus = false;
      }
    })
  }
  
  
  @action('切换分支')
  setOptionItem = (obj, val, callback) => {
    let arr = [];
    this.divideNodeArr.map((v, index) => {
      if(v.remark == obj.nodeRemark){
        this.divideNodeArr[index].checkItem = val + 1;
        this.divideNodeArr[index].showStatus = false;
      }
        arr = [...arr, v.remark+'_'+v.checkItem];
    })
    if(arr.length == 0) return;
    let str = arr.join(',');
    this.getCellArr({choicedBranch: str}, callback);
  }
  
 
  @action('获取弹出面板操作者')
  getOperator = (nodeid, params = {}) => {
    let newParams = {...params, ...this.baseReqParams};
    if(params.nodeType == 3) {
      newParams.isForecastNode = 1;
    }
    let key = nodeid + "_" + params.nodeType;
    if(!this.operatorMap.has(key)) {
      API.getOperator(newParams).then( data => {
        //预测的节点和真实走过的节点，分开显示
        this.operatorMap.set(key, data.nodes);
        this.operatorInfo = data.nodes;
      })
    } else {
      this.operatorInfo = this.operatorMap.get(key);
    }
  } 


  @action('清理操作者信息数组')
  clearOperatorArr = () => {
    this.operatorInfo = [];
  }

  @action('清理store')
  clearStore = () => {
    this.forecastInfoMap = observable.map ? observable.map({}) : asMap({});
    this.smartGuessStatus = false;
    this.allMapshow = false;
    this.divideNodeArr = [];
    this.isEnd = false;
    this.needloading = false;
  }
  @action('记录按钮被点击')
  setRecordClicked = (key) => {
    if(!this.clickedMap.has(key))
      this.clickedMap.set(key, true);
  }
}